import axios from "axios";
import { useUserStore } from "@/stores/modules/userStore";
import router from "@/router";
// import { useRouter } from "vue-router";
// let router = useRouter();
let request = axios.create({
  baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
  timeout: 5000000,
});
//axios请求拦截器
request.interceptors.request.use(
  (config) => {
    //1.从pinia获取token数据
    let token = useUserStore().userInfo?.token;
    //2.按照后端的要求拼接token数据
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (e) => Promise.reject(e)
);
//axios响应拦截器
request.interceptors.response.use(
  (res) => res.data,
  (e) => {
    const userStore = useUserStore();
    console.log(e);
    // 统一失败提示信息
    ElMessage({
      type: "warning",
      message: e.response.data.message,
    });
    //401  token失效处理
    //1.清除本地数据 2.跳转到登录页面
    if (e.response.status === 401) {
      userStore.clearUserInfo();
      router.push("/login");
    }
    return Promise.reject(e);
  }
);
export default request;
